//
//  ShengChenOrderVC.m
//  ShopDemo
//
//  Created by 飞扬的青春 on 2018/8/7.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "ShengChenOrderVC.h"

#import <AlipaySDK/AlipaySDK.h>
#import "APOrderInfo.h"
#import "APRSASigner.h"
#import "WeixinPayHelper.h"
#import "ShopDetailController.h"

@interface ShengChenOrderVC ()

{
    WeixinPayHelper *helper;
}

@property(nonatomic,strong)NSString *scOrderId;
@property(nonatomic,strong)NSString *miaoshuStr;
@property(nonatomic,strong)NSString *sumprice;
@property(nonatomic,strong)NSString *payType;
@property(nonatomic,strong)NSString *orderStr;



@end

@implementation ShengChenOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scOrderId = @"";
    self.payType = @"";
    [self shengchengOrderMethodWithUrl:self.endstr];
    [self creatViewMethod];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(successNotificAction:) name:@"successful" object:nil];
    
}

-(void)successNotificAction:(NSNotification *)notification{
    if ([notification.userInfo[@"state"]isEqualToString:@"1"]) {
        //支付宝和微信支付成功改变订单状态
        NSString *strurl = [NSString stringWithFormat:@"/dashop/order/app/editStatus.do?order_id=%@&status=%@&pay_way=%@",self.scOrderId,notification.userInfo[@"state"],self.payType];
        NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
        [self OrderStatesMethodWithUrl:endstr];
        if ([self.payliststr isEqualToString:@"立即购买"]) {
            [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -3)] animated:YES];
        }else{
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    
}

-(void)creatViewMethod{
    NSArray *titarr = @[@"微信支付",@"支付宝",@"货到付款"];
//    NSArray *titarr = @[@"支付宝",@"货到付款"];
    NSArray *namearr = @[@"wechatpay_icon.png",@"zhifubaopay_icon.png",@"paywithgoods_icon.png"];
//    NSArray *namearr = @[@"zhifubaopay_icon.png",@"paywithgoods_icon.png"];
    for (int i = 0; i < titarr.count; i ++) {
        UIView *backview = [UIView new];
        backview.tag = 410 + i;
        [self.view addSubview:backview];
        backview.sd_layout
        .topSpaceToView(self.view, 30*kJLXWidthScale + 51*i*kJLXWidthScale)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .heightIs(51*kJLXWidthScale);
        
        UIImageView *imagevi = [UIImageView new];
        imagevi.image = [UIImage imageNamed:namearr[i]];
        [backview addSubview:imagevi];
        imagevi.sd_layout
        .centerYEqualToView(backview)
        .leftSpaceToView(backview, 20*kJLXWidthScale)
        .widthIs(30*kJLXWidthScale)
        .heightIs(30*kJLXWidthScale);
        
        UILabel *lab = [UILabel new];
        lab.text = titarr[i];
        lab.font = [UIFont systemFontOfSize:15*kJLXWidthScale];
        lab.textColor = [UIColor blackColor];
        [backview addSubview:lab];
        lab.sd_layout
        .centerYEqualToView(backview)
        .leftSpaceToView(imagevi, 8*kJLXWidthScale)
        .heightIs(30*kJLXWidthScale)
        .widthIs(110*kJLXWidthScale);
        
        UIImageView *rightimagevi = [UIImageView new];
        rightimagevi.tag = 400 + i;
        [backview addSubview:rightimagevi];
        rightimagevi.image = [UIImage imageNamed:@"rdb_off.png"];
        rightimagevi.sd_layout
        .centerYEqualToView(backview)
        .rightSpaceToView(backview, 10*kJLXWidthScale)
        .widthIs(15*kJLXWidthScale)
        .heightIs(15*kJLXWidthScale);
        
        UIView *lineview = [UIView new];
        lineview.backgroundColor = LineColor;
        [backview addSubview:lineview];
        lineview.sd_layout
        .bottomSpaceToView(backview, 0)
        .leftSpaceToView(backview, 0)
        .rightSpaceToView(backview, 0)
        .heightIs(1);
        backview.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backviewTap:)];
        [backview addGestureRecognizer:tap];
    }
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5*kJLXWidthScale;
    btn.layer.borderColor = [UIColor orangeColor].CGColor;
    btn.layer.borderWidth = 1;
    btn.titleLabel.font = [UIFont systemFontOfSize:17*kJLXWidthScale];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitle:@"确认付款" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(payButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    btn.sd_layout
    .topSpaceToView(self.view, 220*kJLXWidthScale)
    .leftSpaceToView(self.view, 50*kJLXWidthScale)
    .rightSpaceToView(self.view, 50*kJLXWidthScale)
    .heightIs(45*kJLXWidthScale);
}

-(void)payButtonAction:(UIButton *)sender{
    if(self.scOrderId.length > 0){
        if([self.payType isEqualToString:@"bank"]){
            //货到付款
            NSString *strurl = [NSString stringWithFormat:@"/dashop/order/app/editStatus.do?order_id=%@&status=%@&pay_way=%@",self.scOrderId,@"1",@"alipay"];
            NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
            [self OrderStatesMethodWithUrl:endstr];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else if ([self.payType isEqualToString:@"alipay"]){
            NSString *strurl = [NSString stringWithFormat:@"/dashop/alipay/app/alipaybiz.do?ORDER_BODY=%@&ORDER_ID=%@&ORDER_TOTAL=%@",self.miaoshuStr,self.scOrderId,self.sumprice];
            NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
            NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [self ZhiFuMessageMethodWithUrl:newUrlString];
        }else{
            //微信支付
            [self jumpToBizPay];
        }
    }else{
        [self alerWithMessage:@"无法生成订单"];
    }
}


- (NSString *)jumpToBizPay {
    
    if (![WXApi isWXAppInstalled]) {
        KMLog(@"没有安装微信");
        return nil;
    }else if (![WXApi isWXAppSupportApi]){
        KMLog(@"不支持微信支付");
        return nil;
    }
    KMLog(@"安装了微信，支持微信支付");
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/wxpay/weixin/app_pay?ORDER_ID=%@&NAME=%@&ORDER_TOTAL=%@",self.scOrderId,self.miaoshuStr,self.sumprice];
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
      NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self WeiXinMessageMethodWithUrl:newUrlString];
    return @"";
}



//请求加密字符串
-(void)ZhiFuMessageMethodWithUrl:(NSString *)url{
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        self.orderStr = str;
        // 更新UI在主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            // NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:self.orderStr fromScheme:@"ZJLShopdemo" callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
                
            }];
        });
    }] resume];
}

//请求加密字符串
-(void)WeiXinMessageMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        if ([dic[@"RESULT"] integerValue] == 1) {
            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                NSDictionary *dict = dic[@"DATA"];
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req completion:nil];
//                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
            }];
        }
    } failBlock:^(NSError *error) {
        
    }];
    
   
}


-(void)OrderStatesMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        if ([dic[@"result"] integerValue] == 1) {
            
        }
    } failBlock:^(NSError *error) {
        
    }];
    
}

//生成订单
-(void)shengchengOrderMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            if ([dic[@"result"] integerValue] == 1) {
                self.scOrderId = [NSString stringWithFormat:@"%@",dic[@"order_id"]];
                self.miaoshuStr = [NSString stringWithFormat:@"%@",dic[@"goods_name"]];
                self.sumprice = [NSString stringWithFormat:@"%@",dic[@"order_total"]];
                self.successBlock();
            }else{
                [self alerWithMessage:dic[@"message"]];
            }
        }];
    } failBlock:^(NSError *error) {
        
    }];
}

-(void)backviewTap:(UITapGestureRecognizer *)tap{
    UIImageView *image00 = [self.view viewWithTag:400];
    UIImageView *image01 = [self.view viewWithTag:401];
    UIImageView *image02 = [self.view viewWithTag:402];
    if (tap.view.tag == 410) {
        image00.image = [UIImage imageNamed:@"rdb_check.png"];
        image01.image = [UIImage imageNamed:@"rdb_off.png"];
        image02.image = [UIImage imageNamed:@"rdb_off.png"];
        self.payType = @"wechat";
    }else if (tap.view.tag == 411){
        image00.image = [UIImage imageNamed:@"rdb_off.png"];
        image01.image = [UIImage imageNamed:@"rdb_check.png"];
        image02.image = [UIImage imageNamed:@"rdb_off.png"];
        self.payType = @"alipay";
    }else{
        image00.image = [UIImage imageNamed:@"rdb_off.png"];
        image01.image = [UIImage imageNamed:@"rdb_off.png"];
        image02.image = [UIImage imageNamed:@"rdb_check.png"];
         self.payType = @"bank";
    }
}





//封装提示框方法
-(void)alerWithMessage:(NSString *)msg{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        //延迟1秒自动消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}



#pragma mark -
#pragma mark   ==============微信支付行为==============






@end
